<?php

namespace common\models;

use common\component\BaseActiveRecord;
use common\utils\CommonUtil;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "{{%base_admin}}".
 *
 * @property string $id
 * @property string $username
 * @property string $auth_key
 * @property string $last_login_time
 *  @property string $password_hash
 * @property string $login_times
 * @property string $updated_at
 * @property string $created_at
 */
class User extends BaseActiveRecord implements IdentityInterface
{

    /*
     * 临时密码
     */
    public $password;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'zt_admin';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username','password_hash'], 'required'],
            [['last_login_time', 'login_times', 'updated_at', 'created_at'], 'integer'],
            [['username','password'], 'string', 'max' => 32],
            [['auth_key'], 'string', 'max' => 64],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '序列',
            'username' => '用户名',
            'auth_key' => '验证KEY',
            'password_hash' => '密码',
            'password' => '密码',
            'last_login_time' => '最后登录时间',
            'login_times' => '登录次数',
            'updated_at' => '修改时间',
            'created_at' => '创建时间',
        ];
    }

    public function afterFind()
    {
        parent::afterFind();
        $this->ui();
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['created_at'],
                    self::EVENT_BEFORE_UPDATE => ['updated_at']
                ]
            ]
        ];
    }

    public function ui() {
        $this->ui['created_at'] = date("Y-m-d H:i:s",$this->created_at);
    }


    /**
     * 实例化模型对像
     * @param $id
     * @return BaseActiveRecord|null|static
     */
    public static function modelById($id) {
        if (!$id) {
            $model = new self();
        }
        else {
            $model = static::findOne($id);
        }
        return $model;
    }

    /**
     * 列表页数据加载
     */
    public function generateListData($post) {
        //请求参数组装
        $where = ["and"];

        if (!empty($post['username'])) {
            $where[] = ['like','username',trim($post['username'])];
        }

        $query = self::find()->where($where);
        $dataArr = self::table($query,$post);
        return $dataArr;

    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        return $timestamp + $expire >= time();
    }

    public static function findByUsername($username)
    {
        return static::findOne(['username'=>$username]);
    }

    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id]);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    public function getId()
    {
        return $this->getPrimaryKey();
    }

    public function getRealName() {
        return $this->real_name;
    }

    public function getAuthKey()
    {
        return $this->auth_key;
    }

    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    public function validatePassword($password)
    {    $this->password_hash = Yii::$app->security->generatePasswordHash($password);
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }

    public function beforeValidate()
    {
        if (!parent::beforeValidate()) {
            return false;
        }
        if (!empty($this->password)) {
            $this->setPassword($this->password);
            $this->generateAuthKey();
        }
        return true;
    }

    /**
     * 修改帐号信息及密码
     * @param $user_id
     * @param $params
     * @return bool
     */
    public function modifyUserPwd($user_id,$params) {
        $params = array_filter($params);
        $model = self::findOne($user_id);
        if (!$model) {
            $this->addError("id","帐号不存在");
            return false;
        }
        if (isset($params["password"]) && $params["password"]) {
            $model->setPassword($params["password"]);
            $model->generateAuthKey();
            unset($params["password"]);
        }
        $model->setAttributes($params);

        if (!$model->save()){
            $this->addError("id",$model->getErrorsToString());
            return false;
        }
        return true;
    }


    public static function getFieldById($id,$field="real_name") {
        $data = self::loadRowData($id);
        return isset($data[$field])?$data[$field]:"";
    }

    public static function loadRowData($id) {
    }

}
